mod word;

use anyhow::Context;

pub use crate::word::YouDaoDic;

const APP_KEY: &str = "Mk6hqtUp33DGGtoS63tTJbMUYjRrG1Lu";

pub(crate) fn md5(data: &str) -> String {
    return format!("{:x}", md5::compute(data));
}


pub async fn query_word(word: &str) -> anyhow::Result<YouDaoDic> {
    let keyfrom = "webdict";
    let client = "web";
    let language = "en";
    let time = (word.len() + keyfrom.len()) % 10;
    let salt = md5(&format!("{}{}", word, keyfrom));
    let sign = md5(&format!("{}{}{}{}{}", client, word, time, APP_KEY, salt));
    let data = format!("q={}&le={}&t={}&client={}&sign={}&keyfrom={}",
                       word, language, time, client, sign, keyfrom);
    let client = reqwest::Client::new();
    client.post("https://dict.youdao.com/jsonapi_s")
        .query(&[("doctype", "json"), ("jsonversion", "4")])
        .header("content-type", "application/x-www-form-urlencoded")
        .body(data)
        .send()
        .await
        .with_context(|| format!("请求单词结果失败"))?
        .json::<YouDaoDic>()
        .await.with_context(|| format!("解析json数据失败"))
}

#[cfg(test)]
mod tests {
    use anyhow::Context;
    use crate::word::YouDaoDic;
    use super::*;


    #[tokio::test]
    async fn query_word_test() -> anyhow::Result<()> {
        Ok(())
    }
}
